package ucadminlogic

import (
	"context"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"go.uber.org/zap"
	"navi-mumbai/app/rpc/model/pg/usercenter"
	"navi-mumbai/common/key/userkey"
	"navi-mumbai/common/utils"
	"navi-mumbai/common/xerr"

	"navi-mumbai/app/rpc/usercenter/internal/svc"
	"navi-mumbai/app/rpc/usercenter/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type UnbanUserLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUnbanUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UnbanUserLogic {
	return &UnbanUserLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 解封
func (l *UnbanUserLogic) UnbanUser(in *pb.UnbanUserReq) (*pb.UnbanUserResp, error) {
	defer utils.RecoverPanic()

	var err error
	var ua *usercenter.UserAccount
	ua, err = l.svcCtx.UserAccountModel.FindOne(l.ctx, in.Uid)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
	}

	if ua == nil {
		l.Logger.Errorf("user not exist ")
		return nil, xerr.NewGrpcErrCodeMsg(xerr.UserNotExist, "用户不存在")
	}

	if ua.AccountState == userkey.AccountStateNormal {
		l.Logger.Errorf("user not be reopened ")
		return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, "用户未被封禁")
	}

	var ub *usercenter.UserBan
	ub, err = l.svcCtx.UserBanModel.FindOne(l.ctx, in.Uid)
	if err != nil && err != usercenter.ErrNotFound {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
	}
	if ub == nil {
		l.Logger.Errorf("user not be reopened ")
		return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, "用户未被封禁")
	}

	return l.DoUnbanUser(in, ua.AuthKey, ua.AuthType)
}

func (l *UnbanUserLogic) DoUnbanUser(in *pb.UnbanUserReq, authKey string, authType int64) (*pb.UnbanUserResp, error) {
	err := l.svcCtx.UserAccountModel.Trans(l.ctx, func(ctx context.Context, tx sqlx.Session) error {
		// 更新封禁信息
		err2 := l.svcCtx.UserBanModel.UpdateUnbanState(ctx, tx, in.Uid, in.AdminUid)
		if err2 != nil {
			l.Logger.Errorf("err == ", zap.Error(err2))
			return xerr.NewGrpcErrCodeMsg(xerr.DbError, err2.Error())
		}

		// 更新账户状态
		err2 = l.svcCtx.UserAccountModel.UpdateAccountState(ctx, tx, in.Uid, authKey, authType, userkey.AccountStateNormal)
		if err2 != nil {
			l.Logger.Errorf("err == ", zap.Error(err2))
			return xerr.NewGrpcErrCodeMsg(xerr.DbError, err2.Error())
		}
		return nil
	})
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, err
	}

	return &pb.UnbanUserResp{}, nil
}
